package com.felix.netty.c1.byteBuf;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;

import static io.netty.buffer.ByteBufUtil.appendPrettyHexDump;
import static io.netty.util.internal.StringUtil.NEWLINE;

public class example1 {
    private static void log(ByteBuf buffer) {
        int length = buffer.readableBytes();
        int rows = length / 16 + (length % 15 == 0 ? 0 : 1) + 4;
        StringBuilder buf = new StringBuilder(rows * 80 * 2)
                .append("read index:").append(buffer.readerIndex())
                .append(" write index:").append(buffer.writerIndex())
                .append(" capacity:").append(buffer.capacity())
                .append(NEWLINE);
        appendPrettyHexDump(buf, buffer);
        System.out.println(buf.toString());
    }

    public static void main(String[] args) {
        ByteBuf heapBuf = ByteBufAllocator.DEFAULT.heapBuffer(10);
        ByteBuf directBuf = ByteBufAllocator.DEFAULT.directBuffer(10);

        heapBuf.writeBytes(new byte[]{1,2,3,4});
        log(heapBuf);

        heapBuf.writeInt(5);
        log(heapBuf);

        /** 引发扩容 **/
        heapBuf.writeInt(6);
        log(heapBuf);

//        System.out.println(heapBuf.readByte());
//        System.out.println(heapBuf.readByte());
//        System.out.println(heapBuf.readByte());
//        System.out.println(heapBuf.readByte());
//        log(heapBuf);

//
//        heapBuf.markReaderIndex();
//        System.out.println(heapBuf.readInt());
//        log(heapBuf);
//
//        heapBuf.resetReaderIndex();
//        System.out.println(heapBuf.readInt());
//        log(heapBuf);

        /** get方式不影响读指针 **/
        System.out.println(heapBuf.getByte(1));
        log(heapBuf);
    }
}
